//
//  BlueToothManager.m
//  UHealth
//
//  Created by liliang on 15/2/3.
//  Copyright (c) 2015年 gjtx. All rights reserved.
//

#import "BlueToothManager.h"
#import "MBProgressHUD+YCL.h"

@interface BlueToothManager ()<CBCentralManagerDelegate,CBPeripheralDelegate>

@property (nonatomic, strong)CBCentralManager           *manager;   //中央
@property (nonatomic, strong)CBPeripheral               *peripheral;//周边

@property (nonatomic)        CBCentralManagerState       cbCentralManagerState;//中央状态


@property (nonatomic, strong)NSMutableArray             *scannedPeripherals;
@property (nonatomic, strong)NSMutableArray             *advertisementDataArray;
@property (nonatomic, strong)NSMutableArray             *dateArray;

@property (assign, nonatomic)NSUInteger                  peripheralsCountToStop;

@property (copy, nonatomic) LLCentralManagerDiscoverPeripheralsCallback scanBlock;
//@property (copy, nonatomic) LLCentralManagerGetTemperatureValueCallback getTemperatureBlock;

@end

@implementation BlueToothManager

#pragma mark - 接口方法


// 扫描之前先清空之前扫描到的设备和广告数据
- (void)scanForPeripheralsWithServices:(NSArray *)serviceUUIDs
                               options:(NSDictionary *)options
{
    [self.scannedPeripherals removeAllObjects];
    [self.advertisementDataArray removeAllObjects];
    [self.dateArray removeAllObjects];
    self.scanning = YES;
    [self.manager scanForPeripheralsWithServices:serviceUUIDs
                                         options:options];
}

// 限时扫描，回调
- (void)scanForPeripheralsByInterval:(NSUInteger)aScanInterval
                            services:(NSArray *)serviceUUIDs
                             options:(NSDictionary *)options
                          completion:(LLCentralManagerDiscoverPeripheralsCallback)aCallback
{
    self.scanBlock = aCallback;
    [self scanForPeripheralsWithServices:serviceUUIDs
                                 options:options];
    [NSObject cancelPreviousPerformRequestsWithTarget:self
                                             selector:@selector(stopScanForPeripherals)
                                               object:nil];
    [self performSelector:@selector(stopScanForPeripherals)
               withObject:nil
               afterDelay:aScanInterval];
}


// 限时扫描所有服务，回调
- (void)scanForPeripheralsByInterval:(NSUInteger)aScanInterval
                          completion:(LLCentralManagerDiscoverPeripheralsCallback)aCallback
{
    [self scanForPeripheralsByInterval:aScanInterval
                              services:nil
                               options:@{CBCentralManagerScanOptionAllowDuplicatesKey : @YES}
                            completion:aCallback];
}

// 扫描
- (void)scanForPeripherals
{
    [self scanForPeripheralsWithServices:nil
                                 options:@{CBCentralManagerScanOptionAllowDuplicatesKey : @YES}];
}

- (void)stopScanForPeripherals
{
    self.scanning = NO;
    [self.manager stopScan];
    
    [NSObject cancelPreviousPerformRequestsWithTarget:self
                                             selector:@selector(stopScanForPeripherals)
                                               object:nil];
    if (self.scanBlock) {
        self.scanBlock(self.scannedPeripherals, self.advertisementDataArray, self.dateArray);
    }
    self.scanBlock = nil;
}

#pragma mark - Setter and Getter
- (BOOL)isCentralReady
{
    return (self.manager.state == CBCentralManagerStatePoweredOn);
}

- (NSString *)centralNotReadyReason
{
    return [self stateMessage];
}

- (NSArray *)peripherals
{
    return self.scannedPeripherals;
}

#pragma mark = 私有方法
- (NSString *)stateMessage
{
    NSString *message = nil;
    switch (self.manager.state) {
        case CBCentralManagerStateUnsupported:
            message = @"The platform/hardware doesn't support Bluetooth Low Energy.";
            break;
        case CBCentralManagerStateUnauthorized:
            message = @"The app is not authorized to use Bluetooth Low Energy.";
            break;
        case CBCentralManagerStateUnknown:
            message = @"Central not initialized yet.";
            break;
        case CBCentralManagerStatePoweredOff:{
        
            message = @"Bluetooth is currently powered off.";
            [MBProgressHUD showError:@"未打开蓝牙"];
        }
            break;
        case CBCentralManagerStatePoweredOn:
            break;
        default:
            break;
    }
    return message;
}


#pragma mark - 代理方法
- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
    self.cbCentralManagerState = central.state;
    NSString *message = [self stateMessage];
    if (message) {
        NSLog(@"本机蓝牙状态：%@", message);
    }
}


// 发现设备
- (void)centralManager:(CBCentralManager *)central
 didDiscoverPeripheral:(CBPeripheral *)peripheral
     advertisementData:(NSDictionary *)advertisementData
                  RSSI:(NSNumber *)RSSI
{
    
    // 只添加 TEM 开头的设备
    
    if (![self.scannedPeripherals containsObject:peripheral] && [peripheral.name hasPrefix:@"TEM"]) {
        // 保存设备，广告数据，时间0
        [self.scannedPeripherals     addObject:peripheral];
        [self.advertisementDataArray addObject:advertisementData];
        [self.dateArray              addObject:[NSDate date]];
    }
    
    // 扫描到一定数量后 停止扫描
    if ([self.scannedPeripherals count] >= self.peripheralsCountToStop) {
        [NSObject cancelPreviousPerformRequestsWithTarget:self
                                                 selector:@selector(stopScanForPeripherals)
                                                   object:nil];
        [self stopScanForPeripherals];
    }
}


#pragma mark - 初始化方法
static BlueToothManager *sharedBlueToothManagerInstance = nil;
+ (BlueToothManager *)sharedManager
{
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        sharedBlueToothManagerInstance = [[BlueToothManager alloc] init];
    });
    return sharedBlueToothManagerInstance;
}

- (id)init {
    if (self = [super init]) {
        _manager                = [[CBCentralManager alloc] initWithDelegate:self
                                                                       queue:dispatch_get_global_queue(0, 0)];
        _cbCentralManagerState  = _manager.state;
        _scannedPeripherals     = [NSMutableArray array];
        _advertisementDataArray = [NSMutableArray array];
        _dateArray              = [NSMutableArray array];
        _peripheralsCountToStop = NSUIntegerMax;
    }
    return self;
}

+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedBlueToothManagerInstance = [super allocWithZone:zone];
    });
    
    return sharedBlueToothManagerInstance;
}


@end
